package com.shxzz.easy12306.framework.starter.idempotent.core;

import cn.hutool.core.collection.CollUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * 幂等处理上下文
 * <p>
 *     记录幂等处理过程中的上下文信息，便于不同阶段共享信息
 * </p>
 * @author shxzz
 * @create 2024-02-22-23:32
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IdempotentContext {
    private static final ThreadLocal<Map<String, Object>> CONTEXT = new ThreadLocal<>();

    public static Object getValue(String key) {
        Map<String, Object> map = CONTEXT.get();
        if(CollUtil.isNotEmpty(map)) {
            return map.get(key);
        }
        return null;
    }

    public static void put(String key, Object value) {
        Map<String, Object> map = CONTEXT.get();
        if(CollUtil.isEmpty(map)) {
            map = new HashMap<>();
            CONTEXT.set(map);
        }
        map.put(key, value);
    }

    public static void remove() {
        CONTEXT.remove();
    }
}
